package org.dromara.mendmix.gateway.filter;

import org.dromara.mendmix.gateway.GatewayConstants;
import org.dromara.mendmix.gateway.helper.RequestContextHelper;
import org.dromara.mendmix.gateway.model.BizSystemModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * 
 * @description <br>
 * @author <a href="mailto:vakinge@gmail.com">jiangwei</a>
 * @date 2022年4月7日
 */
public class GlobalPostRouteFilter implements GlobalFilter, Ordered, CommandLineRunner  {

	private static Logger logger = LoggerFactory.getLogger("org.dromara.mendmix");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    	//
    	final boolean debugMode = RequestContextHelper.isDebugMode(exchange);
    	if(exchange.getAttribute(GatewayConstants.CONTEXT_IGNORE_FILTER) != null) {
    		return chain.filter(exchange);
    	}
    	BizSystemModule module = RequestContextHelper.getCurrentModule(exchange);
    	//转发网关
    	if(module.isSubGateway()) {
    		return chain.filter(exchange);
    	}
    	//
		boolean rewriteBody = true; //	TODO 忽略的情况
		if(rewriteBody) {
			RewriteBodyServerHttpResponse newResponse = new RewriteBodyServerHttpResponse(exchange,module);
			return chain.filter(exchange.mutate().response(newResponse).build());
		}
		return chain.filter(exchange);
    }
    
    
    @Override
    public int getOrder() {
    	return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
    }


	@Override
	public void run(String... args) throws Exception {}

	
}